package project.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import project.model.History;
import project.model.Option;
import project.model.Question;
import project.service.HistoryService;
import project.service.OptionService;

import java.time.LocalDateTime;
import java.util.List;

@RequestMapping(value = "/option")
@CrossOrigin
@RestController
public class OptionController {
    @Autowired
    OptionService optionService;
    @Autowired
    HistoryService historyService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping
    public int addOption(@ModelAttribute Option option) {
        System.out.println("Option added");
        return optionService.addOption(option);
    }
    @ApiOperation("查询指定题目下的所有选项")
    @GetMapping(value = "/{tid}")
    public List<Option> getOptionsByTid(@PathVariable String tid) {
        System.out.println("Options list get successfully!");
        Integer idInt =tid==null?0:Integer.parseInt(tid);
        String loginName=(String)redisTemplate.opsForValue().get("loginName");
        if (loginName!=null){
        return optionService.getOptionsByTid(idInt);
        }else return null;
    }
    @PutMapping
    public int updateOption(@ModelAttribute Option option) {
        System.out.println("Option updated");
        return optionService.updateOption(option);
    }

    @DeleteMapping
    public int deleteOption(@RequestParam String oid) {
        System.out.println("Option deleted successfully!");
        Integer idInt =oid==null?0:Integer.parseInt(oid);

        return  optionService.deleteOption(idInt);
    }
    @ApiOperation("根据题目id获得随机选项")
    @GetMapping(value = "/select/{tid}")
    public Option generateRandom(@PathVariable String tid,@RequestParam String loginName){
        Integer idInt =tid==null?0:Integer.parseInt(tid);
        List<Option> options = optionService.getOptionsByTid(idInt);
        Option option = optionService.generateRandom(options);
        //存入历史记录
        History history = new History();

        Integer Uid = (Integer) redisTemplate.opsForHash().get(loginName, "uid");
        if (Uid!=null) history.setUid(Uid);
        history.setTid(idInt);
        history.setResult(option.getContent());
        history.setCreate_time(String.valueOf(LocalDateTime.now()));
        historyService.addHistory(history);
        return option;
    }

}
